package com.gougou.controller;

import com.gougou.shiro.token.GougouToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Created by EX-ZHANZHENQIANG001 on 2018-04-28.
 */
@Controller
public class LoginController {

    /**
     * 初始化载入登陆页面
     * @return
     */
    @RequestMapping("/login")
    public String loginInit() {
        return "/login";
    }


    /**
     * 登陆提交处理
     * @param userName
     * @param passWord
     * @return
     */
    @RequestMapping("/submitLogin")
    public String submitLogin(@RequestParam String userName, @RequestParam String passWord) {
        try {
            //判断用户名密码是否为空
            if(!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(passWord)) {
                //登陆认证
                Subject subject = SecurityUtils.getSubject();
                System.out.println(userName);
                System.out.println(passWord);
                GougouToken token  = new GougouToken(userName, passWord);
                System.out.println(token.toString());
                subject.login(token);
                //获取用户的权限

                //跳转到首页
                return "redirect:/home/init.do";
            }
        } catch (AuthenticationException e) {
            System.out.println("用户认证失败！");
            e.printStackTrace();
        }
        //跳转到登陆页面
        return "redirect:/login.do";
    }


    /**
     * 退出登陆
     * @return
     */
    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.do";
    }



}
